package com.bjpowernode.web.controller;

import com.bjpowernode.common.P2PConstants;
import com.bjpowernode.common.ResultObject;
import com.bjpowernode.model.FinanceAccount;
import com.bjpowernode.model.IncomeRecord;
import com.bjpowernode.model.RechargeRecord;
import com.bjpowernode.model.User;
import com.bjpowernode.model.ext.BidLoanInfo;
import com.bjpowernode.service.*;
import com.bjpowernode.web.service.RealNameService;
import com.bjpowernode.web.service.SmsService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;

@Controller
public class UserController {

    @DubboReference(interfaceClass = UserService.class)
    private UserService userService;

    @Resource
    private SmsService smsService;

    @Resource
    private RealNameService realNameService;

    @DubboReference(interfaceClass = BidInfoService.class)
    private BidInfoService bidInfoService;


    @DubboReference(interfaceClass = FinanceAccountService.class)
    private FinanceAccountService financeAccountService;

    @DubboReference(interfaceClass = RechargeService.class)
    private RechargeService rechargeService;

    @DubboReference(interfaceClass = IncomeRecordService.class)
    private IncomeRecordService incomeRecordService;

    /**************************注册功能************************************/
    //注册页面
    @GetMapping("/loan/page/register")
    public String registryPage(Model model){

        return "register";
    }

    //ajax，查询手机号是否注册过
    @GetMapping("/loan/checkPhone")
    @ResponseBody
    public ResultObject checkPhoneRegister(@RequestParam("phone") String phone){
        ResultObject ro =ResultObject.buildError();

        if (phone!=null&&!phone.equals("")){
            User  user=userService.queryByPhone(phone);
            if (user==null){//1.手机号格式不对 2.没有找到
                ro=new ResultObject();
                ro.setCode(0);
                ro.setMessage("可以注册");
                ro.setData("");
            }
        }
        return ro;
    }

    //发送短信
    @GetMapping("/loan/sendSms")
    @ResponseBody
    public ResultObject sendSms(@RequestParam("phone") String phone){
        ResultObject ro =ResultObject.buildError();

        if (phone!=null&&!"".equals(phone)){
            String code=smsService.sendSms(phone);
            if (!"error".equals(code)){
                ro.setCode(0);
                ro.setMessage("发送验证码成功");
                ro.setData(code);//验证码
            }
        }
        return ro;
    }

    @PostMapping("/loan/register")
    @ResponseBody
    public ResultObject registerUser(@RequestParam("phone") String phone,
                                     @RequestParam("pwd") String pwd,
                                     @RequestParam("smsCode") String smsCode,
                                     HttpSession session){

        ResultObject ro =ResultObject.buildError();
        //数据验证,commons-lang3工具库提供：
        // isAnyEmpty有任意一个为null或者"",就返回true
        //!isAnyEmpty=isNoneEmpty:有任意一个为null或者"",就返回false;全都不为null或者""返回true
        if(StringUtils.isNoneEmpty(phone,pwd,smsCode)){
            //请求参数有值
            if (phone.length()==11){
                if (smsService.checkSmsCode(phone,smsCode)){
                    //可以注册
                    User user = userService.register(phone,pwd);
                    if (user.getLastLoginTime()==null){
                        //注册成功
                        ro =new ResultObject(0,"注册成功","");
                        //把注册的用户放入到session中
                        session.setAttribute(P2PConstants.SESSION_USER,user);
                    }else {
                        ro =new ResultObject(1004,"手机号已经注册过了");
                    }
                }else {
                    //短信验证码无效
                    ro=new ResultObject(1003,"短信验证码无效");
                }
            }else {
                //手机号不正确
                ro =new ResultObject(1002,"手机号不正确");
            }
        }else {
            //参数有""或者null
            ro=new ResultObject(1001,"手机号不正确");
        }
        return ro;
    }


    /***************************注册功能完成*********************************/


    /***************************实名认证*********************************/
    @GetMapping("/loan/page/realName")//跳转到实名认证页面
    public String realNamePage(Model model,HttpSession session){

        //
        User user = (User) session.getAttribute(P2PConstants.SESSION_USER);
        model.addAttribute("phone",user.getPhone());
        return "realName";
    }

    //实名认证
    @PostMapping("/loan/realName")
    @ResponseBody
    public ResultObject realName(Model model,HttpSession session,
                                @RequestParam("phone") String phone,
                                 @RequestParam("card") String idCard,
                                 @RequestParam("name") String name){
        ResultObject ro = ResultObject.buildError();
        //有任意一个为空返回false
        if (StringUtils.isAnyEmpty(phone,idCard,name)){
            ro=new ResultObject(10001,"请求数据不正确");
        }else if (phone.length()!=11){
            ro=new ResultObject(10002,"手机号不正确");
        }else if (!(idCard.length()==15||idCard.length()==18)){
            ro =new ResultObject(10003,"身份证号格式不正确");
        }else {
            User user= (User) session.getAttribute(P2PConstants.SESSION_USER);
            if (!phone.equalsIgnoreCase(user.getPhone())){
                ro=new ResultObject(10004,"手机号不是注册时使用的手机号");
            }
            //做实名认证
            boolean result = realNameService.realName(phone,idCard,name);
            if (result){
                //更新u_user的idCard和name字段的值
                User updateUser =new User();
                updateUser.setPhone(phone);
                updateUser.setIdCard(idCard);
                updateUser.setName(name);
                int rows = userService.modifyUser(updateUser);
                if (rows>0){
                    ro =new ResultObject(0,"认证成功");
                }
            }
        }
        return ro;
    }

    /**********************用户中心***************************/
    //进入个人中心：我的小金库
    @GetMapping("/loan/myCenter")
    public String myCenterPage(Model model,HttpSession session){

        User user= (User) session.getAttribute(P2PConstants.SESSION_USER);
        //1.获取可用金额
        BigDecimal accountMoney =new BigDecimal("0");
        FinanceAccount financeAccount = financeAccountService.queryAccountByUid(user.getId());
        if (financeAccount!=null){
            accountMoney =financeAccount.getAvailableMoney();
        }

        //2.用户的投资记录
        List<BidLoanInfo> bidLoanInfoList = bidInfoService.queryBidInfoByUid(user.getId());

        //3.用户的充值成功记录
        List<RechargeRecord> rechargeRecordsList = rechargeService.queryRechargeRecordByUid(user.getId());

        //4.最近收益记录
        List<IncomeRecord> incomeRecordList= incomeRecordService.queryIncomeByUid(user.getId());

        model.addAttribute("incomeRecordList",incomeRecordList);
        model.addAttribute("bidLoanInfoList",bidLoanInfoList);
        model.addAttribute("accountMoney",accountMoney);
        model.addAttribute("rechargeRecordsList",rechargeRecordsList);
        return "myCenter";
    }


    @GetMapping("/loan/page/login")
    public String pageLogin(String returnUrl,Model model){
        System.out.println("returnUrl========"+returnUrl);
        model.addAttribute("returnUrl",returnUrl);
        return "login";
    }

    //登录的方法
    @PostMapping("/loan/login")
    @ResponseBody
    public ResultObject login(@RequestParam("phone") String phone,
                              @RequestParam("MD5password") String password,
                              HttpSession session){
        ResultObject ro =ResultObject.buildError();
        //验证请求参数
        if(StringUtils.isAnyEmpty(phone,password)){
            ro=new ResultObject(10001,"请求参数缺少值");
        }else {
            //登录
            User user =userService.login(phone,password);
            //把user保存到session中
            if (user!=null){
                session.setAttribute(P2PConstants.SESSION_USER,user);
                ro=new ResultObject(0,"登录成功");
            }
        }
        return ro;
    }

    //退出登录
    @GetMapping("/loan/logout")
    public String logout(HttpSession session){
        session.removeAttribute(P2PConstants.SESSION_USER);
        session.invalidate();
        //回到首页
        return "redirect:/index";

    }

    //查询账户的金额
    @GetMapping("/loan/account")
    @ResponseBody
    public ResultObject queryAccount(HttpSession session){
        ResultObject ro =ResultObject.buildError();
        User user = (User) session.getAttribute(P2PConstants.SESSION_USER);
        if (user!=null){
            FinanceAccount financeAccount=financeAccountService.queryAccountByUid(user.getId());
            if (financeAccount!=null){
                ro =new ResultObject(0,"查询成功",financeAccount.getAvailableMoney());
            }
        }
        return ro;
    }
}
